package com.example.imchat.controller.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.example.imchat.R;
import com.example.imchat.model.Model;
import com.example.imchat.model.bean.UserInfo;
import com.hyphenate.chat.EMClient;

public class SplashActivity extends Activity {
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            //如果当前activity已经退出，不处理handler中得消息
            if (isFinishing()){
                return;
            }
            toMainorLogin();
            //判断进入主界面还是登录界面
        }

    };

    private void toMainorLogin() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                //判断当前账号是否登录过
                if(EMClient.getInstance().isLoggedInBefore()){//登陆过

                    //获取当前用户登录得信息
                    UserInfo account = Model.getInstance().getUserAccountDao().getAccountByHxId(EMClient.getInstance().getCurrentUser());
                    if (account == null){
                        //跳转到登录界面
                        Intent intent = new Intent(SplashActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }else {
                        //登陆成功后加载联系人和群组两张表的方法
                        Model.getInstance().loginSuccess(account);
                        //跳转到主界面
                        Intent intent = new Intent(SplashActivity.this,MainActivity.class);
                        startActivity(intent);
                    }
                    //跳转到主界面
                    Intent intent = new Intent(SplashActivity.this,MainActivity.class);
                    startActivity(intent);
                }else{
                    //没登陆过
                    //跳转到登录界面
                    Intent intent = new Intent(SplashActivity.this,LoginActivity.class);
                    startActivity(intent);
                }
                //结束当前界面
                finish();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        //发送两秒钟得延迟
        handler.sendMessageDelayed(Message.obtain(),2000);
    }
}
